const fs = require('fs-extra');
const path = require('path');
const Core = require('./src/Core/index.js');
const Store = require('./src/Store/index.js');
const Window = require('./src/Window/index.js');
const Finder = require('./src/Finder/index.js');
const TaskPublisher = require('./src/TaskPublisher');
const HOUSE_TYPE = require('./src/constant');
const prompts = require('prompts');

class Worker {
	constructor(options = {}) {
		this.chalk = null;

		this.finder = new Finder();
		this.core = new Core();
		this.store = new Store();
		this.tasker = new TaskPublisher();
		this.window = new Window();
	}

	async getChalk() {
		if (!this.chalk) {
			const { default: chalk } = await import('chalk');

			this.chalk = chalk;
		}

		return Promise.resolve(this.chalk);
	}

	async log(message, type = 'green') {
		const chalk = await this.getChalk();

		console.log(chalk[type](message));
	}

	async exec(type = HOUSE_TYPE.ER_SHOU_FANG, options = {
		city: '天津',
		area: '',
		page: 10,
		cookie: ''
	}) {
		const result = [];
		const urls = this.tasker.create(type, options);

		for (const url of urls) {
			let html = null;

			try {
				const config = {};

				if (options.cookie) {
					try {
						config['cookie'] = fs.readFileSync(options.cookie, 'utf-8');
					} catch (error) {
						await this.log('error: cookie设置失败', 'red');

						config['cookie'] = '';
					}
				}

				html = await this.finder.load(url, config);
			} catch (error) {
				await this.log('❌' + url + ' 读取失败', 'red');

				continue;
			}

			const data = this.core.pause(type, html, {});

			await this.log('✅' + url + ' 读取完成', 'blue');

			result.push(...data);
		}

		const total = await this.store.save(type, options.city, options.area, result);

		return total;
	}

	async bootstrap() {
		try {
			await this.log('贝壳找房数据爬虫程序启动完成...');

			const { type, city, area, page, cookie } = await this.window.open();

			const total = await this.exec(type, {
				city,
				page,
				area,
				cookie
			});

			await this.log(`程序执行完成, 共获取${page}页数据, 总计${total}条`);

			await prompts({
				type: 'text',
				message: '请按任意键退出程序',
			});

			return;

		} catch (error) {
			await this.log(`程序终端已退出...`, 'red');
		}
	}
}

module.exports = Worker;

